<script lang="tsx" setup>
import { systemTitle } from '@/base'
import { ref, h } from 'vue'
import { NDropdown, NIcon, NModal, NInput, NButton } from 'naive-ui'
import * as GlobalAPI from '@/api'
interface Props {
    transparent?: boolean
    hasBorder?: boolean
    showDefaultPage?: boolean
    conversationList?: any
    AppName: string
}
const props = withDefaults(defineProps<Props>(), {  // 将 defineProps 的结果赋值给 props 变量
    transparent: true,
    hasBorder: true,
    showDefaultPage: true,
    AppName:'',
    conversationList: {
        title: '' 
    }
})

// 添加对话框相关状态
const showEditModal = ref(false)
const conversationTitle = ref('日常友好交流开场')
const editingTitle = ref('')
// 使用计算属性获取当前对话标题
const currentTitle = computed(() => {
  return props.conversationList?.title || localStorage.getItem('title') || '新对话'  
  // return props.conversationList?.title || '新对话'  

})
// 打开编辑对话框
const openEditModal = () => {
  editingTitle.value = currentTitle.value
  showEditModal.value = true
}

// 关闭编辑对话框
const closeEditModal = () => {
  showEditModal.value = false
}

// 确认编辑
const  confirmEdit = async() => {
  if (editingTitle.value.trim()) {
    // 触发事件通知父组件更新标题
    const res = await GlobalAPI.update_user_record(props.conversationList.chatId,editingTitle.value)
    if (res.ok) {
       
        window.$ModalMessage.success(`编辑成功`)
        emit('update-title', editingTitle.value)
        closeEditModal()
    }
    
  }

}

// 添加下拉菜单选项
const dropdownOptions = [
    {
        label: '编辑名称',
        key: 'edit',
        icon: () => h('svg', {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "0 0 24 24",
            width: "16",
            height: "16",
            fill: "none",
            stroke: "currentColor",
            'stroke-width': "2",
            'stroke-linecap': "round",
            'stroke-linejoin': "round"
        }, [
            h('path', { d: "M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" }),
            h('path', { d: "M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" })
        ])
    },
    {
        label: () => h('span', { style: 'color: #f56c6c;' }, '删除对话'),
        key: 'delete',
        icon: () => h('svg', {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "0 0 24 24",
            width: "16",
            height: "16",
            fill: "none",
            stroke: "#f56c6c",
            'stroke-width': "2",
            'stroke-linecap': "round",
            'stroke-linejoin': "round"
        }, [
            h('polyline', { points: "3 6 5 6 21 6" }),
            h('path', { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" }),
            h('line', { x1: "10", y1: "11", x2: "10", y2: "17" }),
            h('line', { x1: "14", y1: "11", x2: "14", y2: "17" })
        ])
    }
]



const handleToRepo = () => {
    const link = ref('https://github.com/apconw/sanic-web')
    window.open(link.value, '_blank')
}
// 添加删除对话框相关状态
const showDeleteModal = ref(false)

// 打开删除确认对话框
const openDeleteModal = () => {
  showDeleteModal.value = true
}

// 关闭删除确认对话框
const closeDeleteModal = () => {
  showDeleteModal.value = false
}

// 确认删除
const confirmDelete = async() => {
  console.log('确认删除对话:', conversationTitle.value)
  const res = await GlobalAPI.delete_user_record(props.conversationList.chatId)
    if (res.ok) {
  
        emit('delete-conversation')
  
        window.$ModalMessage.success(`删除成功`)
        closeDeleteModal()
    }
  // 这里添加实际的删除逻辑

}

// 处理下拉菜单选择
const handleSelect = (key) => {
    console.log('选择了:', key)
    if (key === 'edit') {
      openEditModal()
    } else if (key === 'delete') {
      openDeleteModal()
    }
}
const upTitle=ref('')
// 定义事件
const emit = defineEmits(['update-title', 'delete-conversation'])

onMounted(() => {
  if(localStorage.getItem('title')){
    upTitle.value = localStorage.getItem('title')
    console.log('upTitle:', upTitle.value)
  }
  console.log('NavBar mounted, conversationList:', props.conversationList)
  console.log('NavBar title:', props.conversationList?.title)
})

// 添加监听器观察变化
watch(() => props.conversationList, (newVal) => {
  console.log('conversationList changed:', newVal)
  console.log('新的title值:', newVal?.title)
}, { deep: true })
</script>

<template>
    <header
        class="navigation-nav-header-container b-b"
        :class="[
            transparent ? 'bg-bgcolor' : 'bg-transparent',
            hasBorder ? 'b-b-#000/8 b-b-solid' : 'b-b-transparent'
        ]"
    >
        <div class=""></div>
        <div class="">
            <div flex="" px-36px>
                <div
                    flex="~ items-center justify-center"
                    style="
                        font-family: -apple-system, BlinkMacSystemFont,
                            'Segoe UI', Roboto, 'Helvetica Neue', Arial,
                            sans-serif;
                        font-size: 17px;
                        font-weight: bold;
                        color: #181818;
                        position: relative;
                    "
                    select-none
                    cursor-pointer
                >
                    <div class="flex-1 text-center conversation-title">
                        <div style="display: flex; justify-content: center; align-items: center;">
                            <div v-if="showDefaultPage">
                              {{ AppName?AppName:'新对话' }}  
                            </div>
                            <n-dropdown
                                v-else
                                trigger="click"
                                :options="dropdownOptions"
                                @select="handleSelect"
                                placement="bottom-start"
                            >
                              <div class="dropdown-trigger" style="display: flex; align-items: center;">
                                <!-- {{ conversationTitle }} -->
                                {{ currentTitle }}
                                <n-icon size="16" style="margin-left: 8px; cursor: pointer;">
                                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 320 512"><path d="M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4l96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z" fill="currentColor"></path></svg>
                                </n-icon>
                              </div>
                            </n-dropdown>
                        </div>
                    </div>
                </div>
                <slot name="bottom"></slot>
            </div>
        </div>

        <div class="header-right"></div>
    </header>
    
    <!-- 编辑对话名称的弹窗 -->
    <n-modal
      v-model:show="showEditModal"
      title="编辑对话名称"
      preset="card"
      style="width: 500px; max-width: 90vw;"
      :mask-closable="false"
    >
      <div style="margin-bottom: 20px;">
        <n-input
          v-model:value="editingTitle"
          placeholder="请输入对话名称"
          autofocus
          @keydown.enter="confirmEdit"
        />
      </div>
      <div style="display: flex; justify-content: flex-end; gap: 12px;">
        <n-button  quaternary @click="closeEditModal">取消</n-button>
        <n-button   quaternary @click="confirmEdit">确认</n-button>
      </div>
    </n-modal>
    <n-modal
      v-model:show="showDeleteModal"
      style="width: 500px; max-width: 90vw;"
      :mask-closable="true"
      @close="closeDeleteModal"
    >
      <div class="delete-modal-content">
        <div class="delete-modal-header">
          <div class="delete-icon">
            <n-icon size="24" color="#f56c6c">
              <svg viewBox="0 0 24 24" width="24" height="24">
                <path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16zM11 7h2v6h-2V7zm0 8h2v2h-2v-2z" fill="currentColor"></path>
              </svg>
            </n-icon>
          </div>
          <div class="delete-title">确认删除</div>
          <div class="close-button" @click="closeDeleteModal">
            <n-icon size="20">
              <svg viewBox="0 0 24 24" width="20" height="20">
                <path d="M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z" fill="currentColor"></path>
              </svg>
            </n-icon>
          </div>
        </div>
        
        <div class="delete-modal-body">
          <p>该对话内容将被删除无法恢复</p>
        </div>
        
        <div class="delete-modal-footer">
          <n-button quaternary class="cancel-button" @click="closeDeleteModal">取消</n-button>
          <n-button class="delete-button" type="error" @click="confirmDelete">删除</n-button>
        </div>
      </div>
    </n-modal>
</template>

<style lang="scss" scoped>
.navigation-nav-header-container {
    --at-apply: w-full flex items-center justify-left py-10;
    height: 60px;
    border-top-right-radius: 10px;
    margin-right: 5px;
    border-bottom: 0px;

    .header-left,
    .header-right {
        --at-apply: flex items-center h-full text-16;
    }

    .header-left {
        --at-apply: h-50px;
    }

    .header-right {
        --at-apply: flex items-center h-full text-16;
    }
    // 添加具体的背景颜色
    &.bg-bgcolor {
        // background-color: #f0effe;
        //background: linear-gradient(to right, #f0effe, #ddeefe);
        background-color: #fcfcfc;

        // 替换为你的颜色
    }

    &.bg-transparent {
        background-color: transparent;
    }
}

.conversation-title {
    position: relative;
    
    :deep(.n-dropdown-menu) {
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    }
    
    :deep(.n-dropdown-option) {
        padding: 10px 16px;
        
        &:hover {
            background-color: #f7f7f7;
        }
    }
    
    :deep(.n-dropdown-option-body__prefix svg) {
        margin-right: 8px;
    }
    
    :deep(.n-dropdown-option:last-child) {
        .n-dropdown-option-body__prefix svg {
            stroke: #f56c6c;
        }
    }
}

.dropdown-trigger {
    padding: 6px 12px;
    border-radius: 6px;
    transition: background-color 0.2s ease;
    
    &:hover {
        background-color: #f3f3f3;
    }
}

// 删除确认弹窗样式
.delete-modal-content {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.delete-modal-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  position: relative;
}

.delete-icon {
  margin-right: 10px;
}

.delete-title {
  font-size: 18px;
  font-weight: bold;
}

.close-button {
  position: absolute;
  right: 16px;
  top: 16px;
  cursor: pointer;
}

.delete-modal-body {
  padding: 10px 20px 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.delete-modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
  gap: 12px;
}

.cancel-button {
  background-color: #f2f3f5;
  color: #606266;
  
  &:hover {
    background-color: #e9e9eb;
  }
}

.delete-button {
  background-color: #f56c6c;
  color: white;
  
  &:hover {
    background-color: #f78989;
  }
}
</style>